package com.example.blackmarket.module.SecondHandTrade.ItemDetail;

import android.os.Handler;
import android.util.Log;

import com.example.blackmarket.entities.SuccessResponse;
import com.example.blackmarket.model.BlackMarketApi;
import com.example.blackmarket.callback.IShopCallback;
import com.example.blackmarket.module.Base.BasePresenter;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ItemDetailPresenter extends BasePresenter<ItemDetailView> implements IShopCallback {
    private Handler mHandler;
    public ItemDetailPresenter(ItemDetailView view){
        attachView(view);
        mHandler=new Handler();
    }

    //供view调用，当用户购买或上架商品时，将view请求交给model
    public void setData(String seller_id, String buyer_id, int item_id,int type){
        BlackMarketApi.ItemDetailRequest(seller_id, buyer_id, item_id, type, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    assert response.body() != null;
                    String data = response.body().string();
                    mHandler.post(() -> onSuccess(data));
                }
                else {
                    assert response.body() != null;
                    String msg = "code: "+ response.code() + " body: " +response.body().string();
                    Log.e("response failure",msg);
                    mHandler.post(()->onFail(msg));
                }
            }
        });
    }


    @Override
    public void onComplete() {

    }

    @Override
    public void onError() {

    }

    @Override
    public void onFail(String msg) {
        if(isViewAttached()){
            this.getView().showFailure(msg);
        }
    }

    @Override
    public void onSuccess(Object data) {
        //在onResponse拿到response后就通过response.isSuccessful()判断返回的code是否在[200,300)判断请求是否成功
        Log.e("data",data.toString());
        SuccessResponse response = new Gson().fromJson((String) data,SuccessResponse.class);
        if(response.getSuccess()){
            if(isViewAttached()) {
                this.getView().showSuccess();
            }
        }else{
            if(isViewAttached()) {
                this.getView().showFailure(response.getMessage());
            }
        }

    }
}

